package com.example.victory.exception;

import com.example.victory.filter.SpringBootFilter;
import com.example.victory.utils.JsonHelper;
import com.example.victory.common.web.WebHelper;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import feign.RetryableException;
import io.lettuce.core.RedisConnectionException;
import io.netty.channel.ConnectTimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.data.redis.RedisSystemException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.support.MissingServletRequestPartException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * 统一异常处理，转换成Error对象，返回状态码500
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
   
    @ExceptionHandler(value = Exception.class)
    public HttpError handle(Exception ex) {
        // 设置默认Http状态码为200
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = requestAttributes.getResponse();
        response.setStatus(HttpStatus.OK.value());

        HttpError httpError = null;
        if (ex instanceof GlobalException) {
            httpError = ((GlobalException) ex).getHttpError();
        } else if (ex instanceof JsonParseException || ex instanceof JsonMappingException) {
            httpError = GlobalError.GLOBAL_JSON_ERROR.getHttpError();
        } else if (ex instanceof MaxUploadSizeExceededException) {
            httpError = GlobalError.GLOBAL_MAX_UPLOAD_SIZE_EXCEEDED.getHttpError();
        } else if (ex instanceof MissingServletRequestPartException) {
            httpError = GlobalError.GLOBAL_INPUT_ERROR.getHttpError();
        } else if (ex instanceof HttpRequestMethodNotSupportedException) {
            httpError = GlobalError.GLOBAL_HTTP_METHOD_NOTSUPPORTED.getHttpError();
        } else if (ex instanceof MultipartException) {
            httpError = GlobalError.GLOBAL_UPLOAD_ERROR.getHttpError();
        } else if (ex instanceof org.springframework.http.converter.HttpMessageNotReadableException) {
            httpError = GlobalError.GLOBAL_JSON_REQUEST_RESPONSE_ERROR.getHttpError();
        } else if (ex instanceof org.springframework.dao.DuplicateKeyException || ex instanceof org.springframework.dao.DataIntegrityViolationException) {
            httpError = GlobalError.GLOBAL_SYSTEM_ERROR.getFormatedHttpError(GlobalError.GLOBAL_MYSQL_DUPLICATE_KEY.getCode());
        } else if (ex instanceof org.springframework.web.bind.MethodArgumentNotValidException) {
            List<FieldError> fieldErrors = ((MethodArgumentNotValidException) ex).getBindingResult().getFieldErrors();
            StringBuilder sb = new StringBuilder();
            for (FieldError fieldError : fieldErrors) {
                sb.append(String.format("{属性为：%s，值为：%s，错误信息为：%s},\n", fieldError.getField(), fieldError.getRejectedValue(), fieldError.getDefaultMessage()));
            }
            httpError = GlobalError.GLOBAL_INPUT_VALIDATE_ERROR.getFormatedHttpError(sb.toString());
        } else if (ex instanceof ConnectTimeoutException || ex instanceof RedisConnectionException || ex instanceof RedisConnectionFailureException) {
            httpError = GlobalError.GLOBAL_SYSTEM_ERROR.getFormatedHttpError(GlobalError.GLOBAL_REDIS_CONNECTION_ERROR.getCode());
        } else if (ex instanceof HttpMediaTypeNotSupportedException) {
            httpError = GlobalError.GLOBAL_CONTENT_TYPE_ERROR.getHttpError();
        } else if (ex instanceof RedisSystemException) {
            httpError = GlobalError.GLOBAL_SYSTEM_ERROR.getFormatedHttpError(GlobalError.GLOBAL_REDIS_CONNECTION_ERROR.getCode());
        } else if (ex instanceof RetryableException) {
            httpError = GlobalError.GLOBAL_SYSTEM_ERROR.getFormatedHttpError(GlobalError.GLOBAL_SERVICE_ERROR.getCode());
        } else {
            httpError = GlobalError.GLOBAL_UNKNOWN.getHttpError();
        }

        // 打印异常信息
        if (ex instanceof GlobalException) {
            LogLevelEnum logLevel = ((GlobalException) ex).getLogLevel();
            if (logLevel == LogLevelEnum.WARN) {
                logger.warn(ex.getMessage());
            } else if (logLevel == logLevel.INFO) {
                logger.info(ex.getMessage());
            } else if (logLevel == logLevel.ERROR) {
                logger.error(ex.getMessage());
            } else {
                logger.error(ex.getMessage(), ex);
            }
        } else {
            logger.error(ex.getMessage(), ex);
        }

        httpError.setTimestamp(new Date().getTime());

        // 打印返回结果
        Boolean isDebug = SpringBootFilter.DebugThreadLocal.get();
        if (isDebug != null && isDebug) {
            String json = JsonHelper.toPrettyJson(httpError);
            WebHelper.logEnd(json);
        }

        HttpServletRequest request = requestAttributes.getRequest();
        logger.error("failed url:{}", request.getRequestURL());

        return httpError;
    }
}
